package com.woldier.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woldier.common.BaseContext;
import com.woldier.common.R;
import com.woldier.entity.ShoppingCart;
import com.woldier.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 购物查添加或者数量+
     * @param shoppingCart
     * @return
     */
    @PostMapping("add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        /*设置shoppingCart中的用户id*/
        shoppingCart.setUserId(BaseContext.getCurrentId());
        /*如果购物车中存在对应的dish_id 或者category_id 那么则执行更新*/
        ShoppingCart shoppingCartServiceByUid = shoppingCartService.getByUid(shoppingCart);

        if(shoppingCartServiceByUid!=null){
            /*若查询出来的不为空则进行更新操作*/
            /*进行数量++*/
            shoppingCartServiceByUid.setNumber(shoppingCartServiceByUid.getNumber()+1);
            shoppingCartService.updateById(shoppingCartServiceByUid);
        }else{
            /*若为空 则是新增操作*/
            shoppingCartService.save(shoppingCart);
        }

        return R.success("成功");
    }

    @PostMapping("sub")
    public R sub(@RequestBody ShoppingCart shoppingCart){

        /*封装uid*/
        shoppingCart.setUserId(BaseContext.getCurrentId());
        /*从数据库中查询*/
        ShoppingCart shoppingCart1 = shoppingCartService.getByUid(shoppingCart);

        if(shoppingCart1.getNumber()==1){
            /*若数量为1 删除*/
            shoppingCartService.removeById(shoppingCart1);
        }
        else {
            /* 不为1 则减一 然后update*/
            shoppingCart1.setNumber(shoppingCart1.getNumber()-1);
            shoppingCartService.updateById(shoppingCart1);
        }

        return R.success("成功");
    }


    /**
     * 购物车查询
     * @return
     */
    @GetMapping("list")
    public R getList(){
        List<ShoppingCart> shoppingCarts = shoppingCartService.getByUid(BaseContext.getCurrentId());
        return R.success(shoppingCarts);
    }


    /**
     * 购物车清楚
     */
    @DeleteMapping("clean")
    public R clean(){
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper  = new LambdaQueryWrapper<>();
        /*添加条件 user_id = ??*/
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(lambdaQueryWrapper);
        return R.success("清空完成!");
    }


}
